﻿package ui {
	import com.greensock.TweenLite;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.filters.GlowFilter;
	public class ListBox extends UIItem {
		private var active:ListItem;
		private var collapsed:Boolean = true;
		private var items:Vector.<ListItem>;
		private var fixedWidth:Number = NaN;
		private var shadow:GlowFilter = new GlowFilter(0x000000, 0.2);
		public function ListBox(items:Vector.<ListItem>, defaultData:Object = null) {
			this.items = items;
			
			var defaultIndex:int = 0;
			for (var i:int = 0; i < items.length; i++) {
				var m:ListItem = items[i];
				if (m.data == defaultData) defaultIndex = i;
				m.x = 10;
				m.visible = false;
				m.addEventListener(MouseEvent.CLICK, itemClick);
				addChild(m);
			}
			active = items[defaultIndex];
			//active.alpha = 1;
			active.visible = true;
			active.x = 0;
			switchTo(active);
		}
		override public function get width():Number { 
			return isNaN(fixedWidth) ? active.width : fixedWidth;
		}
		override public function set width(value:Number):void {
			super.width = value;
		}
		private function switchTo(item:ListItem):void {
			items[items.indexOf(item)] = items[0];
			items[0] = item;
			setChildIndex(item, numChildren-1);
		}
		private function itemClick(e:MouseEvent):void {
			var item:ListItem = e.target as ListItem;
			var i:int;
			var m:ListItem;
			if (collapsed) {
				collapsed = false;
				for (i = 0; i < items.length; i++) {
					m = items[i];
					if (item != m) {
						m.visible = true;
						m.filters = [shadow];
						//TweenNano.to(m, 0.1, { "alpha": 1, "y": i*(m.height) } );
						TweenLite.to(m, 0.1, { "alpha": 1, "y": i*(20) } );
					}
				}
			} else {
				collapsed = true;
				switchTo(item);
				for (i = 0; i < items.length; i++) {
					m = items[i];
					m.filters = [];
					TweenLite.to(m, 0.1, { "alpha": m == item ? 1 : 0, "y": 0, "x": item == m ? 0 : 10 } );
				}
				if (active != item) {
					active = item;
					dispatchEvent(new ListEvent(ListEvent.SELECT, item));
				}
			}
		}
	}
}